//
//  CarnivalsSubCategoriesTableDataViewController.m
//  PartyAnimal
//
//  Created by Hilary Muludiang on 3/13/12.
//  Copyright 2012 Muludiang. All rights reserved.
//

#import "CarnivalsSubCategoriesTableDataViewController.h"
#import "PartyAnimalAppDelegate.h"
#import "CarnivalsDetailViewController.h"
#import "iBacchanal.h"
#import "StackMob.h"

@implementation CarnivalsSubCategoriesTableDataViewController

@synthesize carnivalsSubCategoriesTableDataView;
@synthesize carnivalsSubCategoriesTableData;
@synthesize carnivalsDetailViewController;
@synthesize selectedView;
@synthesize contentView;

-(void)getCarnivalsData{

	iBacchanal *bacchanal = [iBacchanal sharedUser];
	
	carnivalsSubCategoriesTableData = [[NSMutableArray alloc] init];
	NSMutableArray *temp = [[NSMutableArray alloc] init];
	for (NSDictionary *carnival in bacchanal.carnivalsData){
		
		NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
		[dateFormat setDateFormat:@"yyyy-MM-dd"];
		NSDate *tempdate = [dateFormat dateFromString:[carnival objectForKey:@"startDate"]];
		[dateFormat setDateFormat:@"yyyy-MM"];
		NSString *tempStrDate = [dateFormat stringFromDate:tempdate];
	
		if ([tempStrDate isEqualToString: bacchanal.selectedYearMonth] && [[carnival objectForKey:@"hidden"] intValue] == 0){
			NSString *ISOCode = @"";
			NSLocale *locale = [[[NSLocale alloc] initWithLocaleIdentifier: @"en_US"] autorelease];
			NSArray *countryArray = [NSLocale ISOCountryCodes];
			for (NSString *countryCode in countryArray) {
				NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
				if ([[locale displayNameForKey:NSLocaleCountryCode value:countryCode] isEqualToString: [carnival objectForKey:@"country"]])
					ISOCode = countryCode;
				
				[pool release];
			}
			[temp addObject:[NSDictionary dictionaryWithObjectsAndKeys: [carnival objectForKey:@"city"],
							 @"city", ISOCode, @"ISOCode", [carnival objectForKey:@"country"], @"country",
							 [carnival objectForKey:@"carnivals_id"], @"carnivalID", nil]];
			NSLog(@"sss: %@", [carnival objectForKey:@"country"]);
		}
				
		[dateFormat release];
	}
	temp = [[[NSSet setWithArray:temp] allObjects] retain] ;
	NSSortDescriptor *citySort = [[[NSSortDescriptor alloc] initWithKey:@"city" ascending:YES selector:@selector(compare:)] autorelease	];
	NSArray *descriptors = [NSArray arrayWithObjects:citySort, nil];
	carnivalsSubCategoriesTableData = [[temp sortedArrayUsingDescriptors:descriptors ] retain];
	[temp release];
}

// Helper function to size views
- (void)fixupAdView:(UIInterfaceOrientation)toInterfaceOrientation {
 	iBacchanal *bacchanal = [iBacchanal sharedUser];
	if (bacchanal.adBanner  != nil) {        
        if (UIInterfaceOrientationIsLandscape(toInterfaceOrientation)) {
            [bacchanal.adBanner  setCurrentContentSizeIdentifier:
			 ADBannerContentSizeIdentifierLandscape];
        } else {
            [bacchanal.adBanner  setCurrentContentSizeIdentifier:
			 ADBannerContentSizeIdentifierPortrait];
        }          
        [UIView beginAnimations:@"fixupViews" context:nil];
        if (bacchanal.adBannerIsVisible) {
            CGRect adBannerFrame = [bacchanal.adBanner  frame];
            adBannerFrame.origin.x = 0;
            adBannerFrame.origin.y = 0;
            [bacchanal.adBanner  setFrame:adBannerFrame];
            CGRect contentViewFrame = contentView.frame;
            contentViewFrame.origin.y = [bacchanal getBannerHeight:toInterfaceOrientation];
            contentViewFrame.size.height = self.view.frame.size.height - [bacchanal getBannerHeight:toInterfaceOrientation];
            contentView.frame = contentViewFrame;
        } else {
			[self hideBanner:toInterfaceOrientation];
        }
        [UIView commitAnimations];
    }   
}

-(void)hideBanner:(UIInterfaceOrientation)toInterfaceOrientation{
	iBacchanal *bacchanal = [iBacchanal sharedUser];
	CGRect adBannerFrame = [bacchanal.adBanner frame];
	adBannerFrame.origin.x = 0;
	adBannerFrame.origin.y = - [bacchanal getBannerHeight:toInterfaceOrientation];
	[bacchanal.adBanner  setFrame:adBannerFrame];
	CGRect contentViewFrame = contentView.frame;
	contentViewFrame.origin.y = 0;
	contentViewFrame.size.height = self.view.frame.size.height + [bacchanal getBannerHeight:toInterfaceOrientation];
	contentView.frame = contentViewFrame;            
 	
}

// Implement AdBannerViewDelegate
#pragma mark ADBannerViewDelegate

- (void)bannerViewDidLoadAd:(ADBannerView *)banner {
   	iBacchanal *bacchanal = [iBacchanal sharedUser];
	if (!bacchanal.adBannerIsVisible) {                
        bacchanal.adBannerIsVisible = YES;
        [self fixupAdView:[UIDevice currentDevice].orientation];
    }
}

- (void)bannerView:(ADBannerView *)banner didFailToReceiveAdWithError:(NSError *)error{
   	iBacchanal *bacchanal = [iBacchanal sharedUser];
	if (bacchanal.adBannerIsVisible)
    {        
        bacchanal.adBannerIsVisible = NO;
        [self fixupAdView:[UIDevice currentDevice].orientation];
    }
}

#pragma mark -
#pragma mark Initialization

/*
- (id)initWithStyle:(UITableViewStyle)style {
    // Override initWithStyle: if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization.
    }
    return self;
}
*/


#pragma mark -
#pragma mark View lifecycle


- (void)viewDidLoad {
    [super viewDidLoad];
	
	iBacchanal *bacchanal = [iBacchanal sharedUser];
	
	NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
	[dateFormat setDateFormat:@"yyyy-MM"];
	NSDate *tempdate = [dateFormat dateFromString: bacchanal.selectedYearMonth ];
	[dateFormat setDateFormat:@"MMMM yyyy"];
	
 self.navigationItem.title = [dateFormat stringFromDate:tempdate];
 [self getCarnivalsData];
	carnivalsSubCategoriesTableDataView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"iBacchanalbkgd.png"]];

    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}



- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
	
	iBacchanal *bacchanal = [iBacchanal sharedUser];
	if (bacchanal.dataChanged){
		[[StackMob stackmob] get:@"carnivals" withCallback:^(BOOL success, id result) {
			if (success) {
				bacchanal.carnivalsData = [[NSArray alloc] initWithArray:result];
				bacchanal.dataChanged = NO;
				 [self getCarnivalsData];
				[carnivalsSubCategoriesTableDataView reloadData];
				// object found, cast result to NSArray* and continue with processing
			} else {
				// unable to retrieve object, cast result to NSError* and inspect code & message
				NSLog(@"Error:");
			}
		}];
	}
	[self.view addSubview:bacchanal.adBanner];
	[self fixupAdView:[UIDevice currentDevice].orientation];
}


-(void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
	[self fixupAdView:toInterfaceOrientation];
}/*
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}
*/

- (void)viewWillDisappear:(BOOL)animated {
	[super viewWillDisappear:animated];
	iBacchanal *bacchanal = [iBacchanal sharedUser];
	[bacchanal.adBanner removeFromSuperview];
}

/*
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
}
*/

// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations.
    return YES; // (interfaceOrientation == UIInterfaceOrientationPortrait);
}


#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    return [self.carnivalsSubCategoriesTableData count];
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }
    
    // Configure the cell...
    //[[cell textLabel] setText:[carnivalsSubCategoriesTableData objectAtIndex:indexPath.row]];
	[[cell textLabel] setText:[[carnivalsSubCategoriesTableData objectAtIndex:indexPath.row] objectForKey:@"city"]];
	NSString *countryFlag = [NSString stringWithFormat:@"%@.png", [[[carnivalsSubCategoriesTableData objectAtIndex:indexPath.row] objectForKey:@"ISOCode"] lowercaseString] ];
	[[cell imageView] setImage:[UIImage imageNamed:countryFlag]];
	
    return cell;
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
	/*NSCharacterSet *nonNumberSet = [[NSCharacterSet characterSetWithRange:NSMakeRange('0',10)] invertedSet];
	 NSString *trimmed = [[cell textLabel].text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
	 BOOL isNumeric = trimmed.length > 0 && [trimmed rangeOfCharacterFromSet:nonNumberSet].location == NSNotFound;
	 NSString *temp = [NSString stringWithFormat:@"%@ (Done)",[cell textLabel].text ];
	 */
	cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
	
	/*if ((isNumeric) && [[cell textLabel].text intValue] < 2012){
	 [[cell textLabel] setTextColor:[UIColor redColor]];
	 [[cell textLabel] setText:temp];	
	 }
	 else{
	 [[cell textLabel] setTextColor:[UIColor blackColor]];
	 }*/
	
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/


/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source.
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
    }   
}
*/


/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/


/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/


#pragma mark -
#pragma mark Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // Navigation logic may go here. Create and push another view controller.
    /*
    <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil];
     // ...
     // Pass the selected object to the new view controller.
    [self.navigationController pushViewController:detailViewController animated:YES];
    [detailViewController release];
    */
	NSLog(@"%@",[carnivalsSubCategoriesTableData objectAtIndex:indexPath.row] );
	CarnivalsDetailViewController *carnivalsDetailView = [[CarnivalsDetailViewController alloc] initWithNibName:@"CarnivalsDetail" bundle:nil];
	self.carnivalsDetailViewController = carnivalsDetailView;
	
	iBacchanal *bacchanal = [iBacchanal sharedUser];
	
	bacchanal.carnivalID = [[carnivalsSubCategoriesTableData objectAtIndex:indexPath.row] objectForKey:@"carnivalID"];
	
	bacchanal.selectedCity = [[carnivalsSubCategoriesTableData objectAtIndex:indexPath.row] objectForKey:@"city"];
	bacchanal.carnivalDate = self.navigationItem.title;
	//carnivalsDetailViewController.selectedView = selectedView;
    [self.navigationController pushViewController:carnivalsDetailView animated:YES];
	[carnivalsDetailView release];
	
	//Reuse NavController
	PartyAnimalAppDelegate *delegate = [[UIApplication sharedApplication] delegate];
	[delegate.partyAnimalNavigatorViewController pushViewController:carnivalsDetailViewController animated:YES];
	
	
}


#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Relinquish ownership any cached data, images, etc. that aren't in use.
}

- (void)viewDidUnload {
    // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
    // For example: self.myOutlet = nil;
}


- (void)dealloc {
	[contentView release];
	[selectedView release];
	[carnivalsDetailViewController release];
	[carnivalsSubCategoriesTableData release];
    [super dealloc];
}


@end

